<?php
namespace App\Repository\Db;

use App\Exceptions\ValidateException;
use App\Repository\Contracts\AdminInterface;
use App\Repository\Contracts\ShiftExchangeInterface;
use App\Repository\Contracts\ShoppingInterface;

/**
 * @Author:: HuangYin
 * @DateTime: 2017-02-24 14:10
 *
 * @Description:
 */
class ShiftExchangeRepository extends Repository implements ShiftExchangeInterface
{
    protected function modelName()
    {
        return 'App\Model\ShiftExchange';
    }

    public function lists($limit, $page, $map = [])
    {
        $query = $this->searchMap($map);
        $total = $query->count();
        $data = $query->orderBy('id', 'desc')->with('admin')->simplePaginate($limit, ['*'], 'page', $page);
        $list = [];
        foreach ($data as $key => $val) {
            $list[$key] = $val;
            $list[$key]['username'] = $val->admin->real_name;
        }

        return $this->simplePaginate('list', $list, $total, ceil($total/$limit), $page);
    }

    public function created(array $data)
    {
        return $this->save($data);
    }

    public function inventory($uid, $number)
    {
        $detail = $this->findBy('number', $number);
        if ($detail)
            return $this->container->make(ShoppingInterface::class)->statistic($uid, $detail->created_at);

        throw new ValidateException('班号不存在');
    }

    public function detail($id)
    {
        $detail = $this->find($id);
        $detail['inventory'] = json_decode($detail->inventory, true);

        return $detail;
    }

    public function updateByNumber($uid, $number)
    {
        $statistic = $this->inventory($uid, $number);
        $this->update(['inventory' => json_encode($statistic)], $number, 'number');

        return $this->container->make(AdminInterface::class)->logout($uid);
    }
}